package com.blog.controller;

import com.blog.constant.MsgConstant;
import com.blog.constant.RedisConstant;
import com.blog.pojo.dto.AdminLoginDTO;
import com.blog.pojo.entity.Admin;
import com.blog.properties.JwtProperties;
import com.blog.result.Result;
import com.blog.service.AdminService;
import com.blog.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.blog.pojo.vo.AdminLoginVO;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//管理员接口
@RestController
@RequestMapping("admin")
@Slf4j
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 管理员登入接口
     * @param adminLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<AdminLoginVO> adminLogin(@RequestBody AdminLoginDTO adminLoginDTO){
        log.info("开始管理员登入校验：{}", adminLoginDTO);

        Admin admin = adminService.login(adminLoginDTO);

        if ( admin == null) {// 没有数据，说明校验不通过
            log.info("校验不通过");
            return Result.error(MsgConstant.LOGIN_FAILED);
        }

        // 校验通过，生成token返回前端
        Map<String, Object> claims= new HashMap<>();// 将id和管理员名称封装进map对象中，用于生成token认证
        claims.put("id", admin.getId());
        claims.put("adminName", admin.getAdminName());
        claims.put("role", JwtProperties.ROLE_ADMIN);  // 使用常量替换 "ADMIN"

        // 生成token
        String token = JwtUtil.createJWT(JwtProperties.secretKey, JwtProperties.time, claims);

        // 将token存入redis中，保证前端的token与后端token的一致，重新登入后，旧token不会立马报废(因为验证时需要从redis中获取)
        ValueOperations valueOperations = redisTemplate.opsForValue();

        // 设置过期时间2小时
        valueOperations.set(RedisConstant.ADMIN_TOKEN_KEY, token, 2, TimeUnit.HOURS);

        // 构建LoginVO对象
        AdminLoginVO loginVO = AdminLoginVO.builder()
            .token(token)
            .id(admin.getId())
            .adminName(admin.getAdminName())
            .nickname(admin.getNickname())
            .avatar(admin.getAdminAvatar())
            .build();

        return Result.success(loginVO);
    }

    @GetMapping
    public Result<Admin> getAdminByName(){
        Admin admin = adminService.getAdminByName();
        return Result.success(admin);
    }
}
